locals {
  welink = "gw"

  availability_zones = data.huaweicloud_availability_zones.this.names
  subnet_cidrs       = [for i, v in data.huaweicloud_availability_zones.this.names : format("192.168.%d.0/20", 16 * i)]
  subnet_gateways    = [for i, v in data.huaweicloud_availability_zones.this.names : format("192.168.%d.1", 16 * i)]
}

resource "huaweicloud_vpc" "this" {
  name                  = var.vpc_name
  cidr                  = var.vpc_cidr
  tags                  = var.vpc_tags
  description           = var.vpc_description
  #enterprise_project_id = var.enterprise_project_id
}

resource "huaweicloud_vpc_subnet" "this" {
  count  = length(local.availability_zones) > 0 ? length(local.availability_zones) : 0

  name              = format("%s-%01d", var.subnet_name, count.index + 1)
  availability_zone = element(local.availability_zones, count.index)
  cidr              = element(local.subnet_cidrs, count.index)
  gateway_ip        = element(local.subnet_gateways, count.index)
  tags              = var.subnet_tags

  vpc_id = huaweicloud_vpc.this.id

  depends_on = [huaweicloud_vpc.this]
}


// 安全组白名单
resource "huaweicloud_vpc_address_group" "this" {
  name = format("%s-group-test", local.welink)
  addresses = [
    "192.168.10.10",
    "192.168.1.1-192.168.1.50"
  ]
}

resource "huaweicloud_networking_secgroup" "this" {
  name                  = format("%s-secgroup_1", local.welink)
  description           = "My security group"
  #enterprise_project_id = var.enterprise_project_id
}

resource "huaweicloud_networking_secgroup_rule" "this" {
  security_group_id = huaweicloud_networking_secgroup.this.id
  direction         = "ingress"
  ethertype         = "IPv4"
  protocol          = "tcp"
  ports             = "80,443"
  remote_ip_prefix  = "0.0.0.0/0"
}

resource "huaweicloud_networking_secgroup_rule" "mysql" {
  security_group_id = huaweicloud_networking_secgroup.this.id
  direction         = "ingress"
  ethertype         = "IPv4"
  protocol          = "tcp"
  ports             = "3306"
  remote_ip_prefix  = var.myip
}

resource "huaweicloud_vpc_eip" "mysql" {
  publicip {
    type = "5_bgp"
  }
  bandwidth {
    name        = "mysql"
    size        = 8
    share_type  = "PER"
    charge_mode = "traffic"
  }
  #enterprise_project_id = var.enterprise_project_id
  depends_on = [huaweicloud_vpc_subnet.this]
}


